<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input placeholder="请输入SPU名称" v-model="SpuParams.spuName"></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select style="width: 240px;" v-model="SpuParams.tmId">
                    <el-option :value="item.id" :label="item.tmName" v-for="item in AllTradeMark"
                        :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" v-model="SpuParams.description" placeholder="请输入SPU名称"></el-input>
            </el-form-item>
            <el-form-item label="SPU照片">
                <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handleUpload">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="SPU销售属性">
                <el-select v-model="saleAttrIdAndValueName"
                    :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个属性未被选择` : '暂无可添加的属性'"
                    style="width: 240px;">
                    <el-option :value="`${item.id}:${item.name}`" :label="item.name"
                        v-for="(item, index) in unSelectSaleAttr" :key="item.id"></el-option>
                </el-select>
                <el-button :disabled="saleAttrIdAndValueName ? false : true" style="margin: 0 10px;" type="primary"
                    size="default" @click="add" icon="plus">添加属性</el-button>
                <el-table :data="saleAttr" border stripe style="margin: 10px 0;">
                    <el-table-column label="序号" align="center" type="index" width="80"></el-table-column>
                    <el-table-column prop="saleAttrName" label="销售属性名称" width="200" align="center"></el-table-column>
                    <el-table-column label="销售属性值">
                        <template #="{ row, $index }">
                            <el-tag style="margin: 0 6px;" v-for="(item, index) in row.spuSaleAttrValueList"
                                :key="row.id" closable :disable-transitions="false"
                                @close="row.spuSaleAttrValueList.splice(index, 1)">
                                {{ item.saleAttrValueName }}
                            </el-tag>
                            <el-input v-model="row.saleAttrValue" v-if="row.flag == true" placeholder="请输入属性值"
                                size="small" style="width: 100px;margin: 0 5px;" @blur="toInput(row)"></el-input>
                            <el-button v-else type="primary" size="small" @click="toEdit(row)" icon="plus"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" align="center">
                        <template #="{ row, $index }">
                            <el-button icon="delete" type="danger" size="small" title="删除SPU"
                                @click="saleAttr.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
                <!-- <el-button :disabled="!saleAttr.length" type="primary" @click="save">保存</el-button> -->
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import type { HasSaleAttr, SaleAttr, SpuImg, SpuData, AllTradeMark, SpuHasImg, SaleAttrResponseData, HasSaleAttrResponseData, Trademark, SaleAttrValue } from '@/api/product/spu/type'
import { reqAddOrUpdateSpu, reqAllTradeMark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr } from '@/api/product/spu/index'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

let $emit = defineEmits(['handleChange'])
const cancel = () => {
    $emit('handleChange', {flag:0,params:'update'})
}

let AllTradeMark = ref<Trademark[]>([])
let imgList = ref<SpuImg[]>([])
let saleAttr = ref<SaleAttr[]>([])
let allSaleAttr = ref<HasSaleAttr[]>([])
let dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref<string>('')
let SpuParams = ref<SpuData>({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
})
let saleAttrIdAndValueName = ref<string>('')

let unSelectSaleAttr = computed(() => {
    let unSelectArr = allSaleAttr.value.filter((item) => {
        return saleAttr.value.every((item1) => {
            return item.name !== item1.saleAttrName
        })
    })
    return unSelectArr
})

const toInput = (row: SaleAttr) => {
    const { baseSaleAttrId, saleAttrValue } = row
    let newSaleAttrValue: SaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: (saleAttrValue as string)
    }

    if (saleAttrValue?.trim() === '') {
        ElMessage({
            type: 'warning',
            message: '属性值不能为空',
        })
        return
    }
    let repeat = row.spuSaleAttrValueList.find((item) => {
        return item.saleAttrValueName === saleAttrValue
    })
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: '属性值不能重复',
        })
        return
    }

    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}
const toEdit = (row: SaleAttr) => {
    row.flag = true
    row.saleAttrValue = ''
}
const add = () => {
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
    let newSaleAttr: SaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
    }
    saleAttr.value.push(newSaleAttr)
    saleAttrIdAndValueName.value = ''
}
async function save() {
    SpuParams.value.spuImageList = imgList.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url,
        }
    })
    SpuParams.value.spuSaleAttrList = saleAttr.value

    let res: any = await reqAddOrUpdateSpu(SpuParams.value)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: SpuParams.value.id ? '修改成功' : '添加成功'
        })
    } else {
        ElMessage({
            type: 'success',
            message: SpuParams.value.id ? '修改失败' : '添加失败'
        })
    }
    $emit('handleChange', {
        flag: 0,
        params: SpuParams.value.id ? 'update' : 'add',
    })
}
const initHasSpuData = async (spu: SpuData) => {
    SpuParams.value = spu

    let res: AllTradeMark = await reqAllTradeMark()
    let res1: SpuHasImg = await reqSpuImageList((spu.id as number))
    let res2: SaleAttrResponseData = await reqSpuHasSaleAttr((spu.id as number))
    let res3: HasSaleAttrResponseData = await reqAllSaleAttr()

    AllTradeMark.value = res.data
    imgList.value = res1.data.map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl,
        }
    })
    saleAttr.value = res2.data
    allSaleAttr.value = res3.data
}

const initAddSpuData = async (c3Id: number | string) => {
    Object.assign(SpuParams.value, {
        category3Id: '',
        spuName: '',
        description: '',
        tmId: '',
        spuImageList: [],
        spuSaleAttrList: [],
        id: ''
    })
    imgList.value = []
    saleAttr.value = []
    saleAttrIdAndValueName.value = ''
    SpuParams.value.category3Id = c3Id
    let res: AllTradeMark = await reqAllTradeMark()
    let res1: HasSaleAttrResponseData = await reqAllSaleAttr()

    AllTradeMark.value = res.data
    allSaleAttr.value = res1.data
}
defineExpose({ initAddSpuData, initHasSpuData })

const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}
function handleRemove() {

}
function handleUpload(file: any) {
    if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jfif') {
        if (file.size / 1024 / 1024 < 3) {
            return true
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件务必小于3M',
            })
            return false
        }
    } else {
        ElMessage({
            type: 'error',
            message: '请上传文件PNG|JPG|GIF|JPG|JFIF',
        })
        return false
    }
}
</script>

<style scoped></style>